package com.graduation.books_borrow.Service.impl;

import com.graduation.books_borrow.repository.UserMapper;
import com.graduation.books_borrow.Service.UserService;
import com.graduation.books_borrow.entity.User;
import com.graduation.books_borrow.ret.R;
import com.graduation.books_borrow.ret.Rcode;
import com.graduation.books_borrow.utils.Md5Util;
import com.graduation.books_borrow.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public R userRegister(User user) {
        User u = new User();
        u.setUsername(user.getUsername());
        if(null == user || null == user.getUsername() || user.getPassword() == null
                ||"".equals(user.getUsername()) || "".equals(user.getPassword())) {
            return R.ret(Rcode.REGISTER_USER_PSW_NULL, Rcode.REGISTER_USER_PSW_NULL_DESC, u);
        }

        User u2 = userMapper.selectUserByName(u);
        if (u2 != null) {
            return R.ret(Rcode.REGISTER_USER_NAME_EXIST, Rcode.REGISTER_USER_NAME_EXIST_DESC, u);
        }

        user.setPassword(Md5Util.getMD5(user.getPassword()));
        user.setAddtime(TimeUtil.getCurrentTimestamp());
        user.setStatus(1);

        boolean ret = userMapper.addUser(user);
        if (ret) {
            return R.ret(Rcode.REGISTER_SUCCESS, Rcode.REGISTER_SUCCESS_DESC, u);
        } else {
            return R.ret(Rcode.REGISTER_EXCEPTION, Rcode.REGISTER_EXCEPTION_DESC, u);
        }

    }

    @Override
    public R userLogin(User user) {
        User u = new User();
        u.setUsername(user.getUsername());
        if(null == user || null == user.getUsername() || user.getPassword() == null
                ||"".equals(user.getUsername()) || "".equals(user.getPassword())) {
            return R.ret(Rcode.REGISTER_USER_PSW_NULL, Rcode.REGISTER_USER_PSW_NULL_DESC, u);
        }

        String password = user.getPassword();
        user.setPassword(Md5Util.getMD5(password));
        user.setStatus(1);
        User user2 = userMapper.selectUserByNamePsw(user);

        if (user2 != null) {
            return R.ret(Rcode.LOGIN_SUCCESS, Rcode.LOGIN_SUCCESS_DESC, u);
        } else {
            return R.ret(Rcode.LOGIN_FAIL, Rcode.LOGIN_FAIL_DESC, u);
        }

    }
}
